﻿using AutoMapper;
using MediatR;
using SmartCity.BasicData.Api.Application.Commond.DepartMent;
using SmartCity.BasicData.Common;
using SmartCity.BasicData.Domain;
using SmartCity.BasicData.Repo;
using System.Collections.Generic;

namespace SmartCity.BasicData.Api.Application.Handler.DepartMent
{
    public class GetDepartmentTreeHandler : IRequestHandler<GetDepartmentTreeCommand, ApiResult<List<DepartMentTreeDTO>>>
    {
        private readonly IBaseRepository<DepartmentsModel> departRepo;
        private readonly IMapper mapper;

        public GetDepartmentTreeHandler(IBaseRepository<DepartmentsModel> departRepo, IMapper mapper)
        {
            this.departRepo = departRepo;
            this.mapper = mapper;
        }

        public Task<ApiResult<List<DepartMentTreeDTO>>> Handle(GetDepartmentTreeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<DepartMentTreeDTO>> result = new ApiResult<List<DepartMentTreeDTO>>();

            result.Data = GetDepartMentTreeDTOTree();
            return Task.FromResult(result);
        }

        public List<DepartMentTreeDTO> GetDepartMentTreeDTOTree(long parentId = 0) {
            var query = departRepo.QueryAllAsync().Result.Where(x => x.ParentId == parentId);
            var list = mapper.Map<List<DepartMentTreeDTO>>(query);
            list.ForEach(d => {
                d.Children = GetDepartMentTreeDTOTree(d.Id);
            });
            return list;
        }

    }
}
